<template>
  <view>
    <view class="color-bg-fff padding-10 margin-10 border-radius-10 shadow">
      <view class="color-333 font-18 font-weight margin-y-10">{{ info.examName }}</view>
      <u-line margin="20rpx 0"></u-line>
      <view class="font-12 margin-bottom-10" v-if="info.examDescription">
        <text class="color-999 margin-right-10">考试描述</text>
        <text class="color-666">{{ info.examDescription }}</text>
      </view>
      <!-- <view class="font-12" v-if="info.scheduleList && info.scheduleList.length > 0">
         <text class="color-999 margin-right-10">考试时间</text>
         <text class="color-666">{{ info.scheduleList[0].startTime }} - {{ info.scheduleList[0].endTime }}</text>
       </view> -->
      <view class="font-12 margin-top-10" v-if="info.remark">
        <text class="color-999 margin-right-10">备注</text>
        <text class="color-666">{{ info.remark }}</text>
      </view>
    </view>
    <view class="color-bg-fff padding-y-15 padding-x-20 margin-10 border-radius-10 shadow flex-start">
      <view class="flex flex-col">
        <view class="font-12 color-999 margin-bottom-5">答题时间</view>
        <view class="flex-start">
          <simple-image src="/static/images/work/icon-time.png" width="40rpx" height="40rpx"></simple-image>
          <view class="margin-left-3">
            <text class="color-333 font-22 font-light">{{ info.examDuration || 0 }}</text>
            <text class="color-666 font-12 margin-left-3">分</text>
          </view>
        </view>
      </view>
      <u-line direction="col" length="100rpx" margin="0 70rpx"></u-line>
      <view class="flex flex-col">
        <view class="font-12 color-999 margin-bottom-5">及格分数</view>
        <view class="flex-start">
          <simple-image src="/static/images/work/icon-score.png" width="40rpx" height="40rpx"></simple-image>
          <view class="margin-left-3">
            <text class="color-333 font-22 font-light">{{ info.passScore || 0 }}</text>
            <text class="color-666 font-12 margin-left-3">分</text>
          </view>
        </view>
      </view>
      <u-line direction="col" length="100rpx" margin="0 70rpx"></u-line>
      <view class="flex flex-col">
        <view class="font-12 color-999 margin-bottom-5">总分</view>
        <view class="flex-start">
          <simple-image src="/static/images/work/icon-score.png" width="40rpx" height="40rpx"></simple-image>
          <view class="margin-left-3">
            <text class="color-333 font-22 font-light">{{ info.totalScore || 0 }}</text>
            <text class="color-666 font-12 margin-left-3">分</text>
          </view>
        </view>
      </view>
    </view>
    <view class="color-bg-fff padding-y-15 padding-x-20 margin-10 border-radius-10 shadow">
      <u-form ref="uForm" :model="form" :rules="rules" label-width="80" label-align="left"
        :labelStyle="{ color: '#333333', fontWeight: 'bold' }">
        <u-form-item label="考试时间" prop="scheduleStartTime" @click="showScheduleChoose = true">
          <u-input v-model="form.scheduleStartTime" border="none" placeholder="请选择考试时段" class="margin-right-10" readonly
            style="pointerEvents: none"></u-input>
        </u-form-item>
      </u-form>
    </view>
    <view class="bottom">
      <view class="padding-x-10">
        <u-button shape="circle" color="#5BA2F9" @click="submitForm">提交报名</u-button>
      </view>
    </view>

    <!-- 考试时间选择弹窗 -->
    <yd-choose :show="showScheduleChoose" title="选择考试时间" :options="scheduleOptions" :dictCode="form.scheduleId"
      @onClose="showScheduleChoose = false" @select="onScheduleSelect" />
  </view>
</template>

<script>
import { getExamation } from '@/api/examation/examation'
import { registerBySchedule } from '@/api/examation/examRegistration'
import YdChoose from '@/components/yd-choose/yd-choose.vue'

export default {
  components: {
    YdChoose
  },
  data() {
    return {
      examId: null, // 考试ID
      showScheduleChoose: false, // 是否显示考试时间选择弹窗
      scheduleOptions: [], // 考试时间选项
      selectedScheduleText: '', // 选中的考试时间显示文本
      info: {
        id: null,
        examName: '',
        examDescription: '',
        examDuration: 0, // 考试时长（分钟）
        totalScore: 0, // 总分
        passScore: 0, // 及格分
        examStatus: '', // 考试状态
        remark: '', // 备注
        scheduleList: [] // 考试场次列表
      },
      form: {
        scheduleId: '', // 选择的考试场次ID
        scheduleStartTime: '', // 考试开始时间
        examId: '' // 考试ID
      },
      rules: {
        scheduleStartTime: [
          { required: true, message: '请选择考试时间', trigger: ['blur'] }
        ]
      }
    }
  },
  onLoad(options) {
    // 获取路由传入的考试ID
    if (options.id) {
      this.examId = options.id;
      this.getExamInfo();
    }
  },
  methods: {
    // 获取考试详细信息
    async getExamInfo() {
      try {
        const res = await getExamation(this.examId);
        if (res.code === 200) {
          this.info = {
            id: res.data.id,
            examName: res.data.examName,
            examDescription: res.data.examDescription,
            examDuration: res.data.examDuration,
            totalScore: res.data.totalScore,
            passScore: res.data.passScore,
            examStatus: res.data.examStatus,
            remark: res.data.remark,
            scheduleList: res.data.scheduleList || []
          };

          // 设置考试ID到表单
          this.form.examId = res.data.id;

          // 初始化考试时间选项
          this.initScheduleOptions();
        } else {
          uni.showToast({
            title: res.msg || '获取考试信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取考试信息失败:', error);
        uni.showToast({
          title: '获取考试信息失败',
          icon: 'none'
        });
      }
    },
    // 初始化考试时间选项
    initScheduleOptions() {
      if (this.info.scheduleList && this.info.scheduleList.length > 0) {
        this.scheduleOptions = this.info.scheduleList.map(schedule => ({
          dictCode: schedule.id,
          dictLabel: `${schedule.startTime} - ${schedule.endTime}`,
          schedule: schedule
        }));
      }
    },
    // 处理考试时间选择
    onScheduleSelect(selectedItem) {
      this.form.scheduleId = selectedItem.dictCode;
      this.form.scheduleStartTime = selectedItem.dictLabel;
      this.showScheduleChoose = false;

      // 手动触发表单验证更新
    },
    submitForm() {
      // 调试信息
      this.$refs.uForm.validate().then(res => {
        // 表单校验通过，显示确认弹框
        uni.showModal({
          title: '确认提交',
          content: '提交报名后无法修改，是否确认提交？',
          success: (modalRes) => {
            if (modalRes.confirm) {
              this.doRegister();
            }
          }
        });
      }).catch(errors => {
        // 校验失败
        console.log('表单校验失败:', errors);
        uni.showToast({
          title: '请选择考试时间',
          icon: 'none'
        });
      });
    },
    // 执行报名
    async doRegister() {
      uni.showLoading({ title: '提交中...' });

      const data = {
        examId: this.form.examId,
        scheduleId: this.form.scheduleId
      };

      const res = await registerBySchedule(data);
      uni.hideLoading();
      if (res.code === 200) {
        uni.showToast({
          title: '报名成功',
          icon: 'success',
          duration: 2000
        });

        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 2000);
      } else {
        // 处理后端返回的错误信息
        let errorMsg = '报名失败';

        if (res.code === 500 && res.msg) {
          // 特殊处理重复报名等业务错误
          errorMsg = res.msg;
        } else if (res.msg) {
          errorMsg = res.msg;
        }

        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 3000
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 30rpx 20rpx 40rpx 20rpx;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.picker-display {
  padding: 20rpx 0;
  color: #333;
  font-size: 28rpx;
  min-height: 40rpx;
  display: flex;
  align-items: center;

  &:empty::before {
    content: '请选择考试时间';
    color: #999;
  }
}
</style>